package org.example.homework.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.homework.entity.User;
import org.example.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    UserService  userService;
    @GetMapping("/users")
    public String userList(Model model) {
        model.addAttribute("users", userService.getAllUsers());
        return "users";
    }

    // 首页
    @GetMapping("/")
    public String indexPage() {
        return "login";
    }

    // 首页
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    // 登录页面
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    // 登录处理
    @PostMapping("/login")
    public String login( String identifier,
                         String password,
                        HttpSession session,
                        Model model) {

        User user = userService.login(identifier, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/index";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    // 注册页面
    @GetMapping("/register")
    public String registerPage() {
        return "registration";
    }

    // 注册处理
//    @PostMapping("/register")
//    public String register(User user, Model model) {
//        try {
//            userService.register(user);
//            return "redirect:/login";
//        } catch (Exception e) {
//            model.addAttribute("error", "注册失败: " + e.getMessage());
//            System.out.println("注册失败: " + e.getMessage());
//            return "redirect:/register";
//        }
//    }
    @PostMapping("/register")
    public String register(
            @ModelAttribute User user,  // 关键修复：添加注解
            Model model,
            HttpServletRequest request  // 用于获取原始参数
    ) {
        try {
            // 调试日志：验证参数绑定
            System.out.println("接收到的ID：" + user.getId());
            System.out.println("原始参数：" + request.getParameterMap());

            userService.register(user);
            return "redirect:/login";
        } catch (Exception e) {
            model.addAttribute("error", "注册失败: " + e.getMessage());
            return "registration";  // 改为返回视图而非重定向，保留错误信息
        }
    }
    // 个人中心
    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "profile";
    }

    // 修改密码
    @PostMapping("/change-password")
    public String changePassword(@RequestParam String oldPassword,
                                 @RequestParam String newPassword,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        try {
            userService.changePassword(user.getId(), oldPassword, newPassword);
            model.addAttribute("success", "密码修改成功");
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
        }

        return "profile";
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }

    // 保存用户
    @PostMapping("/users/save")
    @ResponseBody
    public Map<String, Object> saveUser(@ModelAttribute User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.register(user);
            response.put("success", true);
            response.put("message", "用户添加成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "用户添加失败: " + e.getMessage());
        }
        return response;
    }

    // 删除用户
    @DeleteMapping("/users/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteUser(@PathVariable int id) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.deleteUser(id);
            response.put("success", true);
            response.put("message", "用户删除成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "用户删除失败: " + e.getMessage());
        }
        return response;
    }

    // 更新用户信息
    @PutMapping("/users/update")
    @ResponseBody
    public Map<String, Object> updateUser(@ModelAttribute User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.updateUser(user);
            response.put("success", true);
            response.put("message", "用户信息更新成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "用户信息更新失败: " + e.getMessage());
        }
        return response;
    }
}